package com.itheima.sh.bulk.service.impl;


import com.alibaba.fastjson.JSON;
import com.itheima.sh.bulk.pojo.GoodInfo;
import com.itheima.sh.bulk.pojo.Result;
import com.itheima.sh.bulk.service.SearchService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SearchServiceImpl implements SearchService {

    public Result searchAndParse(Integer page, Integer size, String keyword,String price,String createTime) throws IOException {
        Result result = new Result();
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.200.150", 9200, "http")));
        SearchSourceBuilder builder = new SearchSourceBuilder();
        if (!StringUtils.isBlank(price)){
            String[] range = price.split("-");
            String lte = range[0];
            String gte = range[1].substring(0, range[1].length() - 1);
            builder.query(QueryBuilders.rangeQuery("price").lte(Integer.valueOf(lte)).gte(Integer.valueOf(gte)));
        }
        if (!StringUtils.isBlank(createTime)&&"desc".equals(createTime)){
            builder.sort("create_time", SortOrder.DESC);
        }
        if (!StringUtils.isBlank(createTime)&&"asc".equals(createTime)){
            builder.sort("create_time", SortOrder.ASC);
        }
        builder.query(QueryBuilders.termQuery("title",keyword));
        builder.highlighter(new HighlightBuilder().field("title").preTags("<em>").postTags("</em>"));
        builder.from((page-1)*size).size(size);
        SearchRequest request = new SearchRequest("goods");
        request.source(builder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        SearchHit[] hitsHits = hits.getHits();

        List<GoodInfo> list=new ArrayList<>();
        for (SearchHit hitsHit : hitsHits) {
            String sourceAsString = hitsHit.getSourceAsString();
            GoodInfo goodInfo = JSON.parseObject(sourceAsString, GoodInfo.class);
            Map<String, HighlightField> map = hitsHit.getHighlightFields();
            if (map!=null&&!map.isEmpty()){
                HighlightField highlightField = map.get("title");
                Text[] fragments = highlightField.getFragments();
                String join = StringUtils.join(fragments);
                goodInfo.setTitle(join);
            }
            list.add(goodInfo);
        }
        Long pages=0L;
        if (total%Long.valueOf(size.toString())==0){
           pages=total/size;
        }else {
            pages=total/size+1;
        }
        result.setPages(pages);
        result.setData(list);
        return result;
    }
}
